#pragma once
#include <iostream>
#include <string>
#include <assert.h>
#include <functional>
#include "log.hpp"
#include "Sock.hpp"
#include "Epoll.hpp"

namespace epoll_1
{
    const static int default_revent_max = 64;
    const static int default_port = 8080;
    using func_t = std::function<void(std::string)>;

    class TcpServer
    {

    public:
        TcpServer(func_t func, uint16_t port = default_port, int revent_max = default_revent_max)
            : _port(port), _revent_max(revent_max), _HandlerRequest(func)
        {
            // 网络部分
            _listensock = Sock::Socket();
            Sock::Bind(_listensock, _port);
            Sock::Listen(_listensock);
            logMessage(DEBUG, "init socket, listensock is: %d", _listensock);
            // epoll模型
            _epfd = Epoll::CreateEpoll();
            if (_epfd < 0)
            {
                logMessage(ERROR, "epoll_create fail. %d, %s", errno, strerror(errno));
                exit(6);
            }

            _revent = new struct epoll_event[_revent_max];
            if (Epoll::CtlEpoll(_epfd, EPOLL_CTL_ADD, _listensock, EPOLLIN) < 0)
            {
                logMessage(ERROR, "epoll_ctl fail. %d, %s", errno, strerror(errno));
                exit(7);
            }
            logMessage(DEBUG, "add listensock to epoll sccess. the epfd is %d", _epfd);
        }

        ~TcpServer()
        {
            if (_listensock >= 0)
                close(_listensock);
            if (_epfd >= 0)
                close(_epfd);
            if (_revent)
                delete[] _revent;
        }

        void Start()
        {
            int timeout = 1000;
            while (true)
            {
                LoopOnce(timeout);
            }
        }

    private:
        void LoopOnce(int timeout)
        {
            int ret = Epoll::WaitEpoll(_epfd, _revent, _revent_max, timeout);
            switch (ret)
            {
            case -1:
                logMessage(WARNING, "epoll_wait error, %d, %s", errno, strerror(errno));
                break;
            case 0:
                logMessage(DEBUG, "epoll timeout, try again.");
                break;
            default:
                logMessage(DEBUG, "epoll wait success, get new events.");
                HandlerEvents(ret);
                break;
            }
        }

        void HandlerEvents(int num)
        {
            assert(num > 0);
            for (int i = 0; i < num; ++i)
            {
                uint32_t reve = _revent[i].events;
                int sock = _revent[i].data.fd;
                if (reve & EPOLLIN)
                {
                    if (sock == _listensock)
                        Accepter(sock);
                    else
                        Recever(sock);
                }
            }
        }

        void Accepter(int listensock)
        {
            uint16_t client_port;
            std::string client_ip;
            int serversock = Sock::Accept(listensock, &client_ip, &client_port);
            logMessage(DEBUG, "get a new link success. [%s:%d], sock is %d", client_ip.c_str(), client_port, serversock);

            if (Epoll::CtlEpoll(_epfd, EPOLL_CTL_ADD, serversock, EPOLLIN) < 0)
            {
                logMessage(WARNING, "epoll_ctl serversock error: %d, %s, close %d", errno, strerror(errno), serversock);
                close(serversock);
            }
            logMessage(DEBUG, "epoll_ctl add a new serversock success, sock is %d", serversock);
        }

        void Recever(int serversock)
        {
            char buffer[10240];
            ssize_t n = recv(serversock, buffer, sizeof(buffer) - 1, 0);
            if (n > 0)
            {
                buffer[n] = 0;
                _HandlerRequest(buffer);
            }
            else if (n == 0)
            {
                logMessage(DEBUG, "client[%d] quit, server will close its sock", serversock);
                int ret = Epoll::CtlEpoll(_epfd, EPOLL_CTL_DEL, serversock, 0);
                assert(ret != -1);
                (void)ret;
                close(serversock);
            }
            else
            {
                logMessage(WARNING, "%d sock recv error. the errno is %d, %s. ", serversock, errno, strerror(errno));
                int ret = Epoll::CtlEpoll(_epfd, EPOLL_CTL_DEL, serversock, 0);
                assert(ret != -1);
                (void)ret;
                close(serversock);
            }
        }

    private:
        int _listensock;
        uint16_t _port;
        int _epfd;                   // epoll示例的fd
        struct epoll_event *_revent; // 接受返回事件
        int _revent_max;             // 返回事件最大个数
        func_t _HandlerRequest;      // 服务器业务函数
    };
}